<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>库存详情</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="/css/style.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <div class="container mx-auto px-4 py-8">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-3xl font-bold text-gray-800">库存详情</h1>
            <a href="/" class="btn-secondary">返回首页</a>
        </div>
        
        <!-- 错误消息显示 -->
        <#if errorMessage??>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                ${errorMessage}
            </div>
        </#if>
        
        <!-- 成功消息显示 -->
        <#if successMessage??>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
                ${successMessage}
            </div>
        </#if>
        
        <!-- 出库表单 -->
        <#if inventory??>
            <div class="bg-white rounded-lg shadow-md p-6 mb-8">
                <h2 class="text-xl font-semibold mb-4">出库操作</h2>
                <form action="" method="post" class="space-y-4" id="stockOutForm">
                    <input type="hidden" name="_method" value="stock-out">
                    <div>
                        <label for="quantity" class="block text-sm font-medium text-gray-700">出库数量</label>
                        <input type="number" id="quantity" name="quantity" min="1" required
                               class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    </div>
                    <div>
                        <label for="reason" class="block text-sm font-medium text-gray-700">出库原因</label>
                        <input type="text" id="reason" name="reason" required
                               class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    </div>
                    <button type="submit"
                            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                        确认出库
                    </button>
                </form>
            </div>
            
            <div class="bg-white rounded-lg shadow-md p-6 mb-8">
                <h2 class="text-xl font-semibold mb-4">入库操作</h2>
                <form action="" method="post" class="space-y-4" id="stockInForm">
                    <input type="hidden" name="_method" value="stock-in">
                    <div>
                        <label for="in-quantity" class="block text-sm font-medium text-gray-700">入库数量</label>
                        <input type="number" id="in-quantity" name="quantity" min="1" required
                               class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    </div>
                    <div>
                        <label for="in-reason" class="block text-sm font-medium text-gray-700">入库原因</label>
                        <input type="text" id="in-reason" name="reason" required
                               class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    </div>
                    <button type="submit"
                            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                        确认入库
                    </button>
                </form>
            </div>
            
            <div class="bg-white rounded-lg shadow-md p-6 mb-8">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <h2 class="text-xl font-semibold mb-4">基本信息</h2>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-sm font-medium text-gray-500">产品名称</label>
                                <p class="text-lg">${inventory.productName!}</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-500">库存ID</label>
                                <p class="text-lg">${inventory.inventoryId!}</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-500">当前库存</label>
                                <p class="text-3xl font-bold text-indigo-600">${inventory.quantity!}</p>
                            </div>
                        </div>
                    </div>
                    
                    <div>
                        <h2 class="text-xl font-semibold mb-4">操作统计</h2>
                        <div class="space-y-3">
                            <div class="flex justify-between">
                                <span class="text-gray-600">总入库量</span>
                                <span class="font-medium">0</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">总出库量</span>
                                <span class="font-medium">0</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">最后更新</span>
                                <span class="font-medium">-</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-semibold mb-4">操作记录</h2>
                <div class="mb-4">
                    <button id="timeTravelBtn" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        时间穿梭
                    </button>
                    <select id="eventSelector" class="ml-2 inline-block rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                        <option value="">选择一个事件</option>
                    </select>
                </div>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200" id="eventTable">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">#</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数量</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="eventTableBody">
                            <tr>
                                <td colspan="4" class="px-6 py-4 text-center text-gray-500">暂无操作记录</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        <#else>
            <div class="bg-white rounded-lg shadow-md p-6 text-center">
                <h2 class="text-xl font-semibold mb-4">未找到库存信息</h2>
                <a href="/" class="btn-primary">返回首页</a>
            </div>
        </#if>
    </div>
    
    <script>
        // 获取事件历史并填充表格
        <#if inventory??>
        // 设置表单action路径
        document.addEventListener('DOMContentLoaded', function() {
            // 获取当前页面URL中的inventoryId
            const pathParts = window.location.pathname.split('/');
            const inventoryId = pathParts[pathParts.length - 1];
            
            // 设置出库表单action
            const stockOutForm = document.getElementById('stockOutForm');
            if (stockOutForm) {
                stockOutForm.action = '/details/' + inventoryId;
            }
            
            // 设置入库表单action
            const stockInForm = document.getElementById('stockInForm');
            if (stockInForm) {
                stockInForm.action = '/details/' + inventoryId;
            }
            
            // 获取事件选择器和时间穿梭按钮
            const eventSelector = document.getElementById('eventSelector');
            const timeTravelBtn = document.getElementById('timeTravelBtn');
            
            fetch('/demo/events/' + inventoryId)
                .then(response => response.json())
                .then(events => {
                    const tbody = document.getElementById('eventTableBody');
                    if (events.length > 0) {
                        // 清空"暂无操作记录"行
                        tbody.innerHTML = '';
                        
                        // 添加事件记录
                        events.forEach((event, index) => {
                            const row = document.createElement('tr');
                            let eventType = '';
                            let quantity = 0;
                            let eventId = '';
                            
                            // 根据事件类型判断事件类型
                            if (event.eventType === 'InventoryCreatedEvent') {
                                // InventoryCreatedEvent
                                eventType = '创建库存';
                                quantity = event.initialQuantity;
                                // 创建事件不可撤销
                                eventId = '';
                            } else if (event.eventType === 'StockInRecordedEvent') {
                                // StockInRecordedEvent
                                eventType = '入库';
                                quantity = event.quantity;
                                eventId = event.eventId;
                            } else if (event.eventType === 'StockOutRecordedEvent') {
                                // StockOutRecordedEvent
                                eventType = '出库';
                                quantity = event.quantity;
                                eventId = event.eventId;
                            } else if (event.eventType === 'OperationCancelledEvent') {
                                // OperationCancelledEvent
                                eventType = '撤销操作';
                                quantity = event.quantity;
                                eventId = event.eventId; // 撤销事件也有eventId
                            }
                            
                            // 生成操作列内容
                            let actionCell = '-';
                            if ((eventType === '入库' || eventType === '出库') && eventId) {
                                actionCell = '<button onclick="cancelOperation(\'' + eventId + '\')" class="text-red-600 hover:text-red-900">撤销</button>';
                            }
                            
                            // 构建表格行内容
                            row.innerHTML = 
                                '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">' + (index + 1) + '</td>' +
                                '<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">' + eventType + '</td>' +
                                '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">' + Math.abs(quantity) + '</td>' +
                                '<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">' + actionCell + '</td>';
                            
                            tbody.appendChild(row);
                            
                            // 为时间穿梭功能添加选项
                            if (eventId) {
                                const option = document.createElement('option');
                                option.value = eventId;
                                option.textContent = (index + 1) + '. ' + eventType + ' - ' + Math.abs(quantity);
                                eventSelector.appendChild(option);
                            }
                        });
                    }
                })
                .catch(error => {
                    console.error('获取事件历史失败:', error);
                });
            
            // 时间穿梭功能
            timeTravelBtn.addEventListener('click', function() {
                const selectedEventId = eventSelector.value;
                if (selectedEventId) {
                    // 直接使用选中的事件ID，不再需要特殊处理
                    fetch('/demo/time-travel/' + inventoryId + '/' + selectedEventId)
                        .then(response => response.json())
                        .then(data => {
                            // 显示时间穿梭结果
                            alert('时间穿梭成功！\n产品名称: ' + data.productName + 
                                  '\n库存数量: ' + data.quantity + 
                                  '\n replayedEventsCount: ' + data.replayedEventsCount);
                            
                            // 如果需要更新页面显示，可以在这里添加代码
                            // 例如，更新页面上的库存数量显示
                            const quantityElement = document.querySelector('.text-3xl.font-bold.text-indigo-600');
                            if (quantityElement) {
                                quantityElement.textContent = data.quantity;
                            }
                        })
                        .catch(error => {
                            console.error('时间穿梭失败:', error);
                            alert('时间穿梭失败: ' + error.message);
                        });
                } else {
                    alert('请选择一个事件');
                }
            });
        });
        
        // 撤销操作
        function cancelOperation(eventId) {
            if (confirm('确定要撤销此操作吗？')) {
                // 获取当前页面URL中的inventoryId
                const pathParts = window.location.pathname.split('/');
                const inventoryId = pathParts[pathParts.length - 1];
                
                fetch('/inventory/' + inventoryId + '/cancel', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        eventId: eventId
                    })
                })
                .then(response => response.text())
                .then(result => {
                    alert('撤销操作成功');
                    // 重新加载页面以更新显示
                    location.reload();
                })
                .catch(error => {
                    console.error('撤销操作失败:', error);
                    alert('撤销操作失败: ' + error.message);
                });
            }
        }
        </#if>
    </script>
</body>
</html>